package com.lijinjiang.view;


import com.lijinjiang.listener.MyKeyCall;

import java.awt.Color;
import java.awt.Rectangle;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JLabel;
import javax.swing.JPasswordField;


/**
 * 自定义密码框类
 */
public class MyPasswordField extends JPasswordField {

    /**
     * 密码框
     */
    private static final long serialVersionUID = 65487378352678L;

    JLabel mask = new JLabel();

    final int fontSize = 12;

    public MyPasswordField() {
        super();
        setFont(new java.awt.Font("宋体", 0, fontSize));
    }

    public MyPasswordField(String text) {
        super(text);
        setFont(new java.awt.Font("宋体", 0, fontSize));
    }

    /* 默认显示值 */

    /**
     * @param @param text 参数
     * @return void 返回类型
     * @throws
     * @Description 设置空值时的默认显示
     */
    public void setPlaceholder(String text) {
        addFocusListener(focusThere);
        Rectangle bs = this.getBounds();
        mask.setText(text);
        mask.setForeground(Color.lightGray);
        mask.setBounds(2, 0, bs.width - 2, bs.height - 2);
        mask.setFont(new java.awt.Font("宋体", 0, 12));
        this.add(mask);
    }

    // 添加焦点监听器，监听输入动作
    FocusListener focusThere = new FocusListener() {
        public void focusGained(FocusEvent arg0) {
            mask.setVisible(false);
        }

        public void focusLost(FocusEvent arg0) {
            String text = String.valueOf(getPassword()).trim();
            if (text.length() == 0) {
                mask.setVisible(true);
            }
        }
    };

    // 键盘监听
    public void keyPressedCall(MyKeyCall call) {
        this.call = call;
        addKeyListener(adapter);
    }

    private MyKeyCall call;
    // 键盘监听
    KeyAdapter adapter = new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
            call.callBack(e);
        }
    };
}
